<template>
  <n-space vertical>
    <div
      style="
        position: fixed;
        line-height: 12vh;
        top: 0;
        right: 19rem;
        z-index: 1000;
      "
    >
      <n-popconfirm @positive-click="posConfirm" @negative-click="nagConfirm">
        <template #trigger>
          <n-button type="warning" round>
            <template #icon>
              <n-icon>
                <ReloadOutline />
              </n-icon>
            </template>
            {{ returnQType(props.type) }}
            <div v-if="props.type === '1'">
              <n-divider vertical></n-divider>总分：{{ calSumScore() }}
            </div>
          </n-button>
        </template>
        现在更改问卷类型会清空已创建问题哦<br />
        确定要继续吗？
      </n-popconfirm>
    </div>
    <n-layout
      has-sider
      position="absolute"
      style="width: 100vw"
      :native-scrollbar="false"
      class="q-out"
    >
      <!-- 侧边题目选择栏 -->
      <n-layout-sider
        bordered
        collapse-mode="width"
        :collapsed-width="50"
        :width="150"
        :collapsed="collapsed"
        show-trigger
        @collapse="collapsed = true"
        @expand="collapsed = false"
        class="q-sider"
      >
        <n-menu
          :collapsed="collapsed"
          :collapsed-width="50"
          :collapsed-icon-size="22"
          :options="menuOptions"
          v-model:value="activeKey"
          @update:value="selectQ"
        />
      </n-layout-sider>
      <n-layout
        :native-scrollbar="false"
        class="q"
        content-style="padding:5vh 16vw 0 6vw"
      >
        <div class="q-page" id="q-page">
          <n-page-header>
            <!-- 题目编辑栏 -->
            <div class="q-page-list">
              <vue-draggable-next
                tag="example"
                :list="qArray"
                :animation="200"
                :handle="draggable ? '.n-collapse-item__header' : '1'"
                :move="dragStart"
                @end="dragInfo"
              >
                <transition-group>
                  <div v-for="(q, index) in qArray" :key="q.id">
                    <n-grid :cols="15" :id="q.type + q.id">
                      <n-gi :span="14">
                        <fill-q
                          :index="showIndex ? Number(index) + 1 : 0"
                          v-model:title="q.title"
                          v-model:remark="q.remark"
                          v-model:required="q.required"
                          v-model:checked="q.more.checked"
                          v-if="q.type === 'q-fill'"
                          :open="q.id < 0 ? true : false"
                        ></fill-q>
                        <single-q
                          :index="showIndex ? Number(index) + 1 : 0"
                          v-model:title="q.title"
                          v-model:remark="q.remark"
                          v-model:required="q.required"
                          v-model:options="q.more.options"
                          v-if="q.type === 'q-s'"
                          :open="q.id < 0 ? true : false"
                        ></single-q>
                        <multi-q
                          :index="showIndex ? Number(index) + 1 : 0"
                          v-model:title="q.title"
                          v-model:remark="q.remark"
                          v-model:required="q.required"
                          v-model:options="q.more.options"
                          :open="q.id < 0 ? true : false"
                          v-if="q.type === 'q-m'"
                        ></multi-q>
                        <rate-q
                          :index="showIndex ? Number(index) + 1 : 0"
                          v-model:title="q.title"
                          v-model:remark="q.remark"
                          v-model:required="q.required"
                          v-model:rate="q.more.rate"
                          v-if="q.type === 'q-rate'"
                          :open="q.id < 0 ? true : false"
                        ></rate-q>
                        <locate-q
                          :index="showIndex ? Number(index) + 1 : 0"
                          v-model:title="q.title"
                          v-model:remark="q.remark"
                          v-model:required="q.required"
                          v-if="q.type === 'q-locate'"
                          :open="q.id < 0 ? true : false"
                        ></locate-q>
                        <fill-e-q
                          :index="showIndex ? Number(index) + 1 : 0"
                          v-model:title="q.title"
                          v-model:remark="q.remark"
                          v-model:required="q.required"
                          v-model:checked="q.more.checked"
                          v-model:answer="q.more.answer"
                          v-if="q.type === 'eq-fill'"
                          v-model:score="q.more.score"
                          :open="q.id < 0 ? true : false"
                        ></fill-e-q>
                        <single-e-q
                          :index="showIndex ? Number(index) + 1 : 0"
                          v-model:title="q.title"
                          v-model:remark="q.remark"
                          v-model:required="q.required"
                          v-model:options="q.more.options"
                          v-model:score="q.more.score"
                          v-model:answer="q.more.answer"
                          v-if="q.type === 'eq-s'"
                          :open="q.id < 0 ? true : false"
                        ></single-e-q>
                        <multi-e-q
                          :index="showIndex ? Number(index) + 1 : 0"
                          v-model:title="q.title"
                          v-model:remark="q.remark"
                          v-model:required="q.required"
                          v-model:options="q.more.options"
                          v-model:score="q.more.score"
                          v-model:answer="q.more.answer"
                          :open="q.id < 0 ? true : false"
                          v-if="q.type === 'eq-m'"
                        ></multi-e-q>
                        <apply-q
                          :index="showIndex ? Number(index) + 1 : 0"
                          v-model:title="q.title"
                          v-model:remark="q.remark"
                          v-model:required="q.required"
                          v-model:applys="q.more.applys"
                          :open="q.id < 0 ? true : false"
                          v-if="q.type === 'q-apply'"
                        ></apply-q>
                      </n-gi>
                      <n-gi :span="1">
                        <div class="side-option">
                          <n-button circle size="small" @click="upQ(q.id)">
                            <template #icon>
                              <n-icon><up-icon /></n-icon>
                            </template>
                          </n-button>
                          <n-button circle size="small" @click="downQ(q.id)">
                            <template #icon>
                              <n-icon><low-icon /></n-icon>
                            </template>
                          </n-button>
                          <n-button circle size="small" @click="deleteQ(q.id)">
                            <template #icon>
                              <n-icon><delete-icon /></n-icon>
                            </template>
                          </n-button>
                          <n-button circle size="small" @click="copyQ(q.id)">
                            <template #icon>
                              <n-icon><copy-icon /></n-icon>
                            </template>
                          </n-button>
                          <n-space>
                            <n-button
                              ghost
                              size="tiny"
                              @click="logic(q, Number(index))"
                              >题目关联</n-button
                            >
                          </n-space>
                        </div>
                      </n-gi>
                    </n-grid>
                    <n-divider></n-divider>
                  </div>
                </transition-group>
              </vue-draggable-next>
              <n-empty
                v-show="qArray.length === 0"
                description="暂时还没有题目哦！试试点击左侧题目栏，选择需要添加的题目吧！"
                style="margin-top: 10vh"
              >
                <template #extra>
                  <n-divider></n-divider>
                </template>
                <template #icon>
                  <n-icon>
                    <ArrowBackOutline />
                  </n-icon>
                </template>
              </n-empty>
            </div>
            <!-- 标题 -->
            <template #title>
              <div id="title">
                <n-input
                  autosize
                  maxlength="30"
                  type="text"
                  v-model:value="title"
                  placeholder="标题在此输入哦"
                  style="min-width: 24vw; font-size: 1.5rem"
                  size="large"
                ></n-input>
              </div>
            </template>
            <!-- 副标题 -->
            <template #subtitle>
              {{ subTitle }}
            </template>
            <!-- 备注信息 -->
            <template #header>
              <n-input
                type="textarea"
                placeholder="在这里输入问卷的前置说明信息，问卷发布后信息将显示在最上方"
                autosize
                size="tiny"
                style="min-width: 45%; color: #aaa"
                v-model:value="note"
                :bordered="false"
              />
            </template>
            <!-- 头像功能 -->
            <template #avatar>
              <n-icon :size="48">
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  xmlns:xlink="http://www.w3.org/1999/xlink"
                  t="1630216837848"
                  class="icon"
                  viewBox="0 0 1024 1024"
                  version="1.1"
                  p-id="1765"
                  width="200"
                  height="200"
                >
                  <path
                    d="M538.566052 851.382571c3.840468 5.503341 8.665357 6.1777 11.910261 6.177699h79.667458c46.873564 0.057305 115.136274-8.711406 185.764867-58.781778 2.738367-1.941212 4.104481-3.081175 8.237615-6.28003 1.579985-1.224898 3.599991-6.755868 1.24434-9.68764-2.488681-3.098571-5.371334-3.13541-6.755867-3.111874-3.281743 0.059352-18.971074 1.112334-22.397103 1.112334-32.843012 0-56.218396-6.489808-71.240531-11.33414-25.983791-8.379854-48.914036-21.962198-60.796668-30.88645a82.753749 82.753749 0 0 0-49.774637-16.665565c-27.997658 0-49.818639 19.508309-55.979965 43.376926-1.394766 5.399987-4.835122 19.184945-8.000208 30.040177-4.976338 17.066701-6.948249 23.419386-13.257955 42.441625-0.186242 0.562818-2.933819 7.42204 1.378393 13.598716z"
                    fill="#aec8d5"
                    p-id="1766"
                  />
                  <path
                    d="M76.839039 613.754498c0 141.792377 116.594485 242.862283 238.447741 243.806795h8.027837c15.32401 0.62831 24.38027 10.333346 28.154223 16.888646 3.302209 5.703909 4.879124 11.974729 4.828982 17.670451v43.602054s0.385786 9.360182 7.436366 16.410762c3.764744 3.765767 10.083659 8.248871 18.547425 7.826245 34.544771-1.723248 61.802578-15.941064 81.461313-36.309973 14.011108-14.519692 20.894889-28.845978 24.871457-37.822421 2.578732-6.260587 6.310729-13.866822 21.864984-57.595766 7.807826-21.945825 12.630668-41.061185 17.154705-57.417711 2.666736-9.644661 4.063549-18.541285 9.999748-29.954219 13.155624-25.287943 38.620599-43.729967 69.061912-46.307675 26.690896-2.26253 47.420009 7.820106 58.441017 16.264429 7.902994 6.053879 26.221198 17.776875 45.596478 26.220174 26.692942 11.633968 58.084906 18.176988 87.86107 18.176988 18.806321 0 44.23548-4.353145 68.511373-19.777438 17.349133-11.021008 32.993438-26.087145 45.213761-48.262191 31.997762-62.306045 34.842553-117.354801 34.842553-143.107325V513.835811c0-78.695317-63.802118-142.640698-142.495388-142.640697l-46.381353 0.013303c-8.31027 0-19.954471-4.013407-27.331486-14.813381-6.104021-8.934486-5.879917-17.774829-5.879917-19.287275v-50.395784c0-19.866467 15.567557-34.486442 34.011628-34.486442 17.820877 0 33.775244 14.442944 33.775244 34.130332 0 18.310018 15.332197 33.642215 33.463136 33.642214 20.399609 0 34.308387-16.176424 34.308387-33.910321 0-57.593719-46.796816-101.681844-101.637841-101.681843-25.241894 0-49.506531 9.423627-67.800176 25.909089-18.48705-16.432251-41.720194-25.90909-68.335364-25.909089-53.761438 0-101.137445 44.054355-101.137445 101.726869 0 17.999956 14.493086 33.865295 33.864272 33.865295 19.288299 0 33.909297-15.688307 33.909297-33.775244 0-19.065218 15.554254-33.997302 33.68724-33.997302 17.643845 0 34.085306 13.687744 34.085307 34.174334l0.012279 50.929949s0.522909 11.511171-7.610328 21.375844c-6.971785 8.456602-16.829294 12.489452-26.264177 12.489452H250.258741s-10.695596 0.221034-18.472724-2.133594c-9.394974-2.845815-15.924691-5.716188-24.397666-12.177343-14.22191-10.842952-25.747407-30.309306-25.747408-52.112892 0-19.829628 7.611352-36.94647 21.481244-49.923016 11.998265-11.228739 28.707832-18.813484 48.587602-17.971304 4.208858 0 13.274328 0.905626 23.140023 6.061043 9.68764 5.061272 16.393365 12.907984 17.70729 14.898315l0.030699-0.026606c18.241456 24.121374 45.234227 41.259706 76.259848 46.648436 0.180102 0.020466 0.36839 0.059352 0.535189 0.081865 4.492314 0.682545 10.081613 0.170892 15.193028-4.628414 5.03876-4.732791 5.248537-10.389628 5.248537-12.396331V234.790444c0-4.193509-1.11745-6.962575-2.049682-8.562003-0.934279-1.600451-3.287883-6.000668-9.668197-8.261151-13.859659-4.910846-23.829731-18.053168-23.829732-33.578769 0-15.487739 9.91379-28.677133 23.746844-33.549094 0 0 3.973498-0.961908 7.706519-5.184069 4.339842-4.907777 4.094248-10.576893 4.094248-11.71788v-52.679803c0-2.8847-1.022283-8.839319-5.960759-12.932543-4.932336-4.087085-9.442046-4.699022-14.157441-4.131088-0.212848 0.023536-0.429789 0.066515-0.652869 0.103354-31.547507 5.418406-58.769498 23.302729-76.368318 46.647413l-0.500397 0.629334c-4.601808 6.095835-12.238742 12.585643-22.547529 16.673751-5.131881 2.034333-13.041014 3.804652-19.039635 3.804652v0.023536c-95.302553 0.830925-173.758416 77.470419-173.758416 176.227654v305.45076z m703.32142 50.697659c-12.294001 13.910824-33.516348 15.260565-47.446615 2.971682-13.910824-12.254092-15.248286-33.513278-2.968611-47.435359 12.262278-13.913894 33.516348-15.246239 47.430242-2.968611 13.929244 12.270465 15.250332 33.511231 2.984984 47.432288z"
                    fill="#aec8d5"
                    p-id="1767"
                  />
                </svg>
              </n-icon>
            </template>
            <!-- 额外功能区 -->
            <template #extra>
              <n-button @click="clearAll">清空所有题目</n-button>
              <n-button @click="clearAllLogic">清空所有关联</n-button>
              <n-affix
                :top="100"
                :trigger-top="370"
                positon="absolute"
                class="q-submit"
              >
                <n-space vertical>
                  <n-space vertical style="max-height: 40vh; overflow: auto">
                    <!-- 右侧导航 -->
                    <n-a @click="hashScrollTop">
                      <n-h6 prefix="bar">
                        {{ title ? title : '请输入标题' }}
                      </n-h6>
                    </n-a>
                    <n-a
                      v-for="(q, index) in qArray"
                      :key="q.id"
                      @click="hashScroll(index)"
                    >
                      {{
                        1 +
                        Number(index) +
                        '. ' +
                        q.title.substring(0, 5) +
                        '...'
                      }}
                    </n-a>
                  </n-space>
                  <div style="margin-top: 15vh"></div>
                  <n-button round @click="print" color="#b2adbb">
                    <template #icon>
                      <n-icon><da-yin-icon /></n-icon>
                    </template>
                    打印
                  </n-button>
                  <n-button
                    ghost
                    @click="preview"
                    text-color="#6d8b8d"
                    color="#6d8b8d"
                  >
                    <template #icon>
                      <n-icon><kan-icon /></n-icon>
                    </template>
                    预览
                  </n-button>
                  <n-button @click="submit" type="error">
                    <template #icon>
                      <n-icon><bao-icon /></n-icon>
                    </template>
                    保存问卷
                  </n-button>
                  <n-select
                    v-model:value="moreValue"
                    multiple
                    :options="moreActions"
                    placeholder="选择更多设置"
                  >
                  </n-select>
                </n-space>
              </n-affix>
            </template>
            <template #footer>
              <!-- <div @click="hashScroll('title')">123123</div> -->
              <div style="color: #999">题目已经到底了...</div>
            </template>
          </n-page-header>
        </div>

        <!-- <div class="q-submit">
          <n-space vertical>
            <div style="width: 12vw; margin: 0 auto">
              <n-switch v-model:value="isReleased">
                <template #checked>保存同时发布</template>
                <template #unchecked>先保存不发布</template>
              </n-switch>
            </div>
            <n-button-group vertical>
              <n-button round @click="print" color="#b2adbb">
                <template #icon>
                  <n-icon><da-icon /></n-icon>
                </template>
                打印
              </n-button>
              <n-button ghost @click="preview" color="#6d6664">
                <template #icon>
                  <n-icon><kan-icon /></n-icon>
                </template>
                预览
              </n-button>
              <n-button @click="submit" type="error">
                <template #icon>
                  <n-icon><bao-icon /></n-icon>
                </template>
                保存问卷
              </n-button>
            </n-button-group>
          </n-space>
        </div> -->
      </n-layout>
      <n-modal
        v-model:show="showModal"
        preset="card"
        title="更换问卷类型"
        :bordered="false"
        style="width: 40vw"
      >
        <n-grid :x-gap="15" :y-gap="10" :cols="3">
          <n-grid-item>
            <div class="card">
              <n-card @click="createQ(0)" :bordered="false" hoverable>
                <template #cover>
                  <div style="padding: 1vw">
                    <img src="@images/icon/wj.png" />
                  </div>
                </template>
                <n-space justify="center" class="text"> 空白问卷 </n-space>
              </n-card>
            </div>
          </n-grid-item>
          <n-grid-item>
            <div class="card">
              <n-card :bordered="false" @click="createQ(1)" hoverable>
                <template #cover>
                  <img src="@images/icon/ks.png" />
                </template>
                <n-space justify="center" class="text"> 考试 </n-space>
              </n-card>
            </div>
          </n-grid-item>
          <n-grid-item>
            <div class="card">
              <n-card :bordered="false" @click="createQ(-1)" hoverable>
                <template #cover>
                  <img src="@images/icon/tp.png" />
                </template>
                <n-space justify="center" class="text"> 投票 </n-space>
              </n-card>
            </div>
          </n-grid-item>
          <n-grid-item>
            <div class="card">
              <n-card :bordered="false" @click="createQ(-2)" hoverable>
                <template #cover>
                  <img src="@images/icon/bm.png" />
                </template>
                <n-space justify="center" class="text"> 报名 </n-space>
              </n-card>
            </div>
          </n-grid-item>
          <n-grid-item>
            <div class="card">
              <n-card :bordered="false" @click="createQ(-3)" hoverable>
                <template #cover>
                  <img src="@images/icon/dk.png" />
                </template>
                <n-space justify="center" class="text"> 疫情打卡 </n-space>
              </n-card>
            </div>
          </n-grid-item>
        </n-grid>
      </n-modal>
      <n-modal v-model:show="showLogicModal" :mask-closable="false">
        <n-card style="width: 40vw" :bordered="false" size="huge">
          <template #header-extra>
            <span style="font-size: 0.8rem; color: #999">
              关闭后将自动保存
            </span>
          </template>
          <template #header>
            题目关联 <n-divider vertical></n-divider>
            <span style="font-size: 0.9rem">
              当前题目： {{ qTemp.title }}
            </span>
          </template>
          <n-dynamic-input
            style="width: 30vw"
            v-model:value="qTemp.more.logic.before"
            :on-create="onLogicCreate"
            #="{ index, value }"
          >
            <n-card>
              <template #header> 关联题目{{ index + 1 + ':' }} </template>
              <n-space vertical size="large">
                <n-select
                  v-model:value="value.id"
                  :options="
                    qArray
                      .filter((ele) => {
                        // FIXME如果考试题目有关联题的话
                        return (
                          ele.type === 'q-s' ||
                          ele.type === 'q-m' ||
                          ele.type === 'eq-s' ||
                          ele.type === 'eq-m'
                        );
                      })
                      .filter((ele) => {
                        return findQ(ele.id) < findQ(qTemp.id);
                      })
                      .map((ele) => {
                        return {
                          label:
                            1 +
                            findQ(ele.id) +
                            '. ' +
                            ele.title +
                            '[' +
                            returnType(ele.type) +
                            ']',
                          value: ele.id,
                        };
                      })
                  "
                ></n-select>
                <div
                  style="width: 40vw"
                  v-if="
                    value.id &&
                    (qArray[findQ(value.id)].type === 'q-s' ||
                      qArray[findQ(value.id)].type === 'eq-s')
                  "
                >
                  <n-space>
                    当关联题目{{
                      index + 1
                    }}选择下面其中一个时，“当前题目”才出现
                  </n-space>
                  <n-radio-group v-model:value="value.options[0]">
                    <n-space vertical>
                      <n-radio
                        v-for="(opt, index) in qArray[findQ(value.id)].more
                          .options"
                        :key="index"
                        :value="opt"
                      >
                        {{ opt }}
                      </n-radio>
                    </n-space>
                  </n-radio-group>
                </div>
                <div
                  style="width: 40vw"
                  v-else-if="
                    value.id &&
                    (qArray[findQ(value.id)].type === 'q-m' ||
                      qArray[findQ(value.id)].type === 'eq-m')
                  "
                >
                  <span>当关联题目{{ index + 1 }}选择下面</span>
                  <n-row>
                    <n-input-number
                      placehoder="最少"
                      v-model:value="value.min"
                      :min="0"
                      :max="
                        value.max < value.options.length
                          ? value.max
                          : value.options.length
                      "
                      style="width: 9vw"
                    >
                      <template #prefix> 最少</template>
                    </n-input-number>
                    <n-input-number
                      placeholder="最多"
                      v-model:value="value.max"
                      :min="value.min"
                      :max="qArray[findQ(value.id)].more.options.length"
                      style="width: 9vw"
                    >
                      <template #prefix> 最多</template>
                    </n-input-number>
                    <span style="margin-top: 0.7vh; margin-left: 1vw">
                      “当前题目”才出现
                    </span>
                  </n-row>
                  <n-checkbox-group v-model:value="value.options" :min="1">
                    <n-space vertical>
                      <n-checkbox
                        v-for="(option, index) in qArray[findQ(value.id)].more
                          .options"
                        :key="index"
                        :value="option"
                        :label="option"
                      />
                    </n-space>
                  </n-checkbox-group>
                </div>
              </n-space>
            </n-card>
          </n-dynamic-input>
          <template #footer>
            <n-space justify="space-between">
              <n-button @click="clearLogic(qTemp.id, qTemp)" type="error" ghost>
                清除该题所有关联
              </n-button>
              <n-button
                type="primary"
                style="width: 8vw"
                @click="confirmLogicClose"
              >
                确认
              </n-button>
            </n-space>
          </template>
        </n-card>
      </n-modal>
    </n-layout>
  </n-space>
  <n-drawer
    v-model:show="previewActive"
    placement="bottom"
    mask-closable
    style="height: 100vh; z-index: 2000"
  >
    <n-drawer-content title="问卷预览" closable :native-scrollbar="false">
      <q-preview
        :title="title"
        :note="note"
        :qArray="qArray"
        :showIndex="showIndex"
      ></q-preview>
    </n-drawer-content>
  </n-drawer>
</template>

<script setup lang="ts">
import {
  computed,
  h,
  onMounted,
  onUnmounted,
  onUpdated,
  ref,
  watch,
} from 'vue';
import MultiQ from './components/NormalQuestion/MultiChoiceQ.vue';
import FillQ from './components/NormalQuestion/FillQ.vue';
import RateQ from './components/NormalQuestion/RateQ.vue';
import SingleQ from './components/NormalQuestion/SingleChoiceQ.vue';
import LocateQ from './components/NormalQuestion/LocationQ.vue';
import QPreview from '@views/Questionnaire/QuestionPreview/QuestionPreview.vue';
import FillEQ from './components/ExamQuestion/FillEQ.vue';
import MultiEQ from './components/ExamQuestion/MultiChoiceEQ.vue';
import SingleEQ from './components/ExamQuestion/SingleChoiceEQ.vue';
import ApplyQ from './components/SpecialQuestion/ApplyQ.vue';
import { VueDraggableNext } from 'vue-draggable-next';
import { NIcon } from 'naive-ui';
import {
  RadioButtonOn as RadioIcon,
  CheckmarkDoneCircle as CheckmarkIcon,
  Pencil as FillinIcon,
  Star as MarkIcon,
  LocationSharp as LocationIcon,
  HandRightSharp as ApplyIcon,
  CopyOutline as CopyIcon,
  TrashOutline as DeleteIcon,
  ChevronUpOutline as UpIcon,
  ChevronDownOutline as LowIcon,
  SaveOutline as BaoIcon,
  PrintOutline as DaYinIcon,
  EyeOutline as KanIcon,
  LogoFoursquare,
  ArrowBackOutline,
  ReloadOutline,
} from '@vicons/ionicons5';
import { Ques } from '@api/question';

import { useRouter } from 'vue-router';
import { messageLight } from 'naive-ui/lib/message/styles';
const router = useRouter();

import { useMessage } from 'naive-ui';
import { Json } from '@vicons/carbon';
import { useStore } from 'vuex';
const message = useMessage();

function renderIcon(icon: any) {
  return () => h(NIcon, null, { default: () => h(icon) });
}

// 响应式 padding
// const paddingStyle = computed(() => {
//   return 'padding:5vh 16vw 0 6vw';
//   // return window.innerWidth > 1080 ? 'padding:4vh 16vw 0 6vw' : '0 16vw 1vh 2vw';
// });

const props = defineProps({
  id: {
    default: '0',
    type: String,
  },
  type: {
    // 0 普通空白
    // 1 考试问卷
    // -1 投票问卷
    // -2 报名问卷
    // -3 疫情打卡问卷
    default: '0',
    type: String,
  },
});
const returnQType = (type: string) => {
  switch (Number(type)) {
    case 0:
      return '普通问卷';
    case 1:
      return '考试问卷';
    case -1:
      return '投票问卷';
    case -2:
      return '报名问卷';
    case -3:
      return '疫情打卡问卷';
  }
};
let timer;
onMounted(() => {
  // 建立定时器定时保存
  timer = setInterval(() => {
    save();
  }, 30000);
  // 改变新建、修改状态
  store.commit('changeCreate', true);
  console.log(store.state.isCreate);
  if (id.value !== 0) {
    Ques.getQ({
      id: id.value,
    }).then((res: any) => {
      console.log(res);
      console.log('121323123');
      if (res.data.status === 200) {
        if (res.data.data.qStatus > 0) {
          console.log('res.data.data.qstatus: ', res.data.data.qstatus);
          // 如果是发布了
          window.$message.info('问卷已发布，请停止后再继续编辑');
          router.go(-1);
        } else {
          title.value = res.data.data.title;
          if (res.data.data.showIndex) {
            moreValue.value ? moreValue.value.push('index') : ['index'];
          }
          qArray.value = res.data.data.content;
        }
      } else {
        window.$message.error(res.data.msg);
      }
    });
  } else {
    initQ();
    window.$message.info('可以在左侧选择题型，题目编辑支持拖动哦', {
      closable: true,
      duration: 5000,
    });
  }
});
onUnmounted(() => {
  clearInterval(timer);
  console.log('clear');
});
// 拖拽事件
const dragInfo = () => {
  if (!dragSuccess.value)
    window.$message.error('移动失败!请核对题目的关联关系');
};
const dragSuccess = ref(true);
const dragStart = (evt, originalEvent) => {
  console.log(evt);
  console.log(originalEvent);
  /* 逻辑判断
    上去判断old和new之间有无old的before
    下去判断old是否是其他的before
  */
  let oldIndex = evt.draggedContext.index;
  let newIndex = evt.draggedContext.futureIndex;
  let oldId = qArray.value[oldIndex].id;

  if (oldIndex < newIndex) {
    // 下移
    for (let i = oldIndex + 1; i <= newIndex; i++) {
      let q = qArray.value[i];
      for (let ii = 0; ii < q.more.logic.before.length; ii++) {
        if (q.more.logic.before[ii].id === oldId) {
          dragSuccess.value = false;
          return false;
        }
      }
    }
  } else {
    // 上移
    let beforeIndex = qArray.value[oldIndex].more.logic.before.map((ele) => {
      return ele.id;
    });
    for (let i = oldIndex - 1; i >= newIndex; i--) {
      if (beforeIndex.indexOf(qArray.value[i].id) >= 0) {
        dragSuccess.value = false;
        return false;
      }
    }
  }
  dragSuccess.value = true;
  return true;
};
const canMove = (oldIndex: number, newIndex: number, oldId: number) => {
  if (oldIndex < newIndex) {
    // 下移
    for (let i = oldIndex + 1; i <= newIndex; i++) {
      let q = qArray.value[i];
      for (let ii = 0; ii < q.more.logic.before.length; ii++) {
        if (q.more.logic.before[ii].id === oldId) {
          return false;
        }
      }
    }
  } else {
    // 上移
    let beforeIndex = qArray.value[oldIndex].more.logic.before.map((ele) => {
      return ele.id;
    });
    for (let i = oldIndex - 1; i >= newIndex; i--) {
      if (beforeIndex.indexOf(qArray.value[i].id) >= 0) {
        return false;
      }
    }
  }
  return true;
};

// 问卷基本信息
const title = ref('');
const id = ref(Number(props.id));
const note = ref('');
const subTitle = ref('');
const version = ref('');
const amount = computed(() => {
  qArray.value.length;
});

// 虚拟id 为了区分题目
const fakeID = ref(0);
// 默认题型
const defaultQ = [
  [
    //投票
    {
      id: --fakeID.value,
      type: 'q-s',
      title: '请输入投票标题',
      remark: '',
      required: '必填',
      more: {
        options: [],
        logic: {
          before: [],
        },
      },
    },
  ],
  [
    //报名
    {
      id: --fakeID.value,
      type: 'q-fill',
      title: '姓名',
      remark: '',
      required: '必填',
      more: {
        checked: 'name',
        options: [],
        logic: {
          before: [],
        },
      },
    },
    {
      id: --fakeID.value,
      type: 'q-fill',
      title: '手机号',
      remark: '',
      required: '必填',
      more: {
        checked: 'phone',
        options: [],
        logic: {
          before: [],
        },
      },
    },
    {
      id: --fakeID.value,
      type: 'q-apply',
      title: '您要报名的项目',
      remark: '',
      required: '必填',
      more: {
        applys: [
          {
            option: '项目1',
            left: 5,
            other: '说明信息1',
          },
          {
            option: '项目2',
            left: 5,
            other: '说明信息2',
          },
        ],
        options: [],
        logic: {
          before: [],
        },
      },
    },
  ],
  [
    //疫情打卡
    {
      id: --fakeID.value,
      type: 'q-fill',
      title: '姓名',
      remark: '',
      required: '必填',
      more: {
        checked: 'name',
        options: [],
        logic: {
          before: [],
        },
      },
    },
    {
      id: --fakeID.value,
      type: 'q-fill',
      title: '学号',
      remark: '',
      required: '必填',
      more: {
        checked: 'id',
        options: [],
        logic: {
          before: [],
        },
      },
    },
    {
      id: --fakeID.value,
      type: 'q-s',
      title: '您今天的体温范围是',
      remark: '',
      required: '必填',
      more: {
        options: ['36.2℃及以下', '36.2℃~37.3℃', '37.3℃及以上'],
        logic: {
          before: [],
        },
      },
    },
    {
      id: --fakeID.value,
      type: 'q-s',
      title: '近期有无去过中高风险地区',
      remark: '',
      required: '必填',
      more: {
        options: ['无', '有'],
        logic: {
          before: [],
        },
      },
    },
    {
      id: --fakeID.value,
      type: 'q-s',
      title: '近期有无新冠症状（发热、干咳、乏力等）',
      remark: '',
      required: '必填',
      more: {
        options: ['无', '有'],

        logic: {
          before: [],
        },
      },
    },
    {
      id: --fakeID.value,
      type: 'q-locate',
      title: '您的位置是',
      remark: '',
      required: '必填',
      more: {
        options: [],
        logic: {
          before: [],
        },
      },
    },
  ],
];
const store = useStore();
onUnmounted(() => {
  store.commit('changeCreate', false);
  console.log(store.state.isCreate);
});
console.log('1', -Number(props.type) - 1);
// 题目列表数据
const qArray: any = ref([]);
// 初始化题目模板
const initQ = () => {
  qArray.value =
    Number(props.type) < 0
      ? defaultQ[-Number(props.type) - 1]
      : Number(props.type) === 0
      ? []
      : [
          // 这里是考试问卷
          {
            id: --fakeID.value,
            type: 'eq-fill',
            title: '考生姓名',
            remark: '',
            required: '必填',
            more: {
              checked: 'name',
              score: 0,
              options: [],
              logic: {
                before: [],
              },
            },
          },
          {
            id: --fakeID.value,
            type: 'eq-fill',
            title: '考生学号',
            remark: '',
            required: '必填',
            more: {
              checked: 'id',
              score: 0,
              options: [],
              logic: {
                before: [],
              },
            },
          },
        ];
  console.log('q', qArray.value);
};
// 逻辑关联
const logic = (q: any, index: number) => {
  if (index === 0) {
    window.$message.error('第一题无法创建关联题目');
    return;
  }
  qBackLogic.value = q.more.logic.before;
  qTemp.value = q;
  qTempIndex.value = index;
  showLogicModal.value = true;
};
const showLogicModal = ref(false);
const qTemp: any = ref({});
const qTempIndex = ref(null);
const qBackLogic = ref({});
// 关闭不保存
// const handleLogicClose = () => {
//   console.log('qBackLogic.value: ', qBackLogic.value);
//   qArray.value[findQ(qTemp.value.id)].more.before = qBackLogic.value;
//   console.log(
//     'qArray.value[findQ(qTemp.value.id)]: ',
//     qArray.value[findQ(qTemp.value.id)]
//   );
//   showLogicModal.value = false;
// };
// 关闭保存
const confirmLogicClose = () => {
  showLogicModal.value = false;
};
// 清除逻辑
const clearLogic = (id: number, q: any) => {
  qArray.value.forEach((ele: any) => {
    for (let i = 0; i < ele.more.logic.before.length; i++) {
      console.log('ele.more.logic.before: ', ele.more.logic.before[i]);
      if (ele.more.logic.before[i].id === id) {
        console.log(id);
        ele.more.logic.before.splice(i--, 1);
      }
    }
  });
  q.more.logic.before = [];
  window.$message.success('清除成功');
};
// 新建一个
const onLogicCreate = () => {
  return {
    id: null,
    type: '',
    options: [],
    min: 0,
    max: 1,
  };
};

// 右侧导航
const qNavi = computed(() => {
  qArray.value.forEach((ele: any) => {
    console.log(ele.id);
  });
});
// 找到题目
function findQ(id: number) {
  let found = qArray.value.length;
  for (let i = 0; i < found; i++) {
    console.log('---');
    console.log(qArray.value[i].id);
    if (qArray.value[i].id === id) {
      return i;
    }
  }
  return -1;
}
// 清空题目
const clearAll = () => {
  qArray.value = [];
  window.$message.success('清空问卷成功');
};
// 清空逻辑
const clearAllLogic = () => {
  qArray.value.forEach((q: any) => {
    q.more.logic.before = [];
  });
  window.$message.success('清除逻辑成功');
};
// 删除题目
const deleteQ = (id: number) => {
  let index = findQ(id);
  let len = qArray.value.length;
  if (index < 0 || index >= len) {
    window.$message.error('删除失败!');
    return;
  }
  for (let j = 0; j < len; j++) {
    let ele = qArray.value[j];
    for (let i = 0; i < ele.more.logic.before.length; i++) {
      console.log('ele.more.logic.before: ', ele.more.logic.before[i]);
      if (ele.more.logic.before[i].id === id) {
        window.$message.error('存在依赖逻辑关系，删除失败!');
        return;
      }
    }
  }
  qArray.value.splice(index, 1);
};
// 上移题目
const upQ = (id: number) => {
  let index = findQ(id);
  if (index <= 0 || index >= qArray.value.length) {
    window.$message.error('上移失败!');
    return;
  }
  if (!canMove(index, index - 1, id)) {
    window.$message.error('上移失败!');
    return;
  }
  qArray.value[index] = qArray.value.splice(
    index - 1,
    1,
    qArray.value[index]
  )[0];
};
// 下移题目
const downQ = (id: number) => {
  let index = findQ(id);
  if (index < 0 || index >= qArray.value.length - 1) {
    window.$message.error('下移失败!');
    return;
  }
  if (!canMove(index, index + 1, id)) {
    window.$message.error('下移失败!');
    return;
  }
  qArray.value[index] = qArray.value.splice(
    index + 1,
    1,
    qArray.value[index]
  )[0];
};
// 复制题目
const copyQ = (id: number) => {
  let index = findQ(id);
  if (index === -1) {
    window.$message.error('复制失败!');
    return;
  }
  let tmp = JSON.parse(JSON.stringify(qArray.value[index]));
  tmp.id = --fakeID.value;
  console.log(tmp);
  qArray.value.splice(index + 1, 0, tmp);
};

// 返回type的中文
const returnType = (type: string) => {
  switch (type) {
    case 'q-s':
      return '单选题';
    case 'q-m':
      return '多选题';
    case 'eq-s':
      return '单选题';
    case 'eq-m':
      return '多选题';
    default:
      return '';
  }
};

// drag变位
//选择时
const onChoose = () => {
  window.$message.success('choose！');
};
//改变位置时
const onChange = () => {
  window.$message.success('换位成功！');
};

// 左侧工具栏
const menuOptions = computed(() => {
  if (props.type === '1') {
    //考试问卷
    return [
      {
        label: '单选题',
        key: 'eq-s',
        icon: renderIcon(RadioIcon),
      },
      {
        label: '多选题',
        key: 'eq-m',
        icon: renderIcon(CheckmarkIcon),
      },
      {
        label: '填空题',
        key: 'eq-fill',
        icon: renderIcon(FillinIcon),
      },
      {
        label: '评分题',
        key: 'q-rate',
        icon: renderIcon(MarkIcon),
      },
      {
        label: '报名题',
        key: 'q-apply',
        icon: renderIcon(ApplyIcon),
      },
      {
        label: '定位题',
        key: 'q-locate',
        icon: renderIcon(LocationIcon),
      },
    ];
  } else {
    //其他问卷
    return [
      {
        label: '单选题',
        key: 'q-s',
        icon: renderIcon(RadioIcon),
      },
      {
        label: '多选题',
        key: 'q-m',
        icon: renderIcon(CheckmarkIcon),
      },
      {
        label: '填空题',
        key: 'q-fill',
        icon: renderIcon(FillinIcon),
      },
      {
        label: '评分题',
        key: 'q-rate',
        icon: renderIcon(MarkIcon),
      },
      {
        label: '报名题',
        key: 'q-apply',
        icon: renderIcon(ApplyIcon),
      },
      {
        label: '定位题',
        key: 'q-locate',
        icon: renderIcon(LocationIcon),
      },
    ];
  }
});
// 当前选中的
const activeKey = ref(null);
// 是否折叠
const collapsed = ref(false);
// 选择增加题目
const selectQ = (value: string) => {
  let total = qArray.value.length;
  switch (value) {
    case 'q-apply':
      qArray.value.push({
        id: --fakeID.value,
        type: value,
        title: '',
        remark: '',
        required: '非必填',
        more: {
          logic: {
            before: [],
          },
          applys: [
            {
              option: '1',
              left: 0,
              other: '2',
            },
          ],
        },
      });
      break;
    case 'q-s':
      qArray.value.push({
        id: --fakeID.value,
        type: value,
        title: '',
        remark: '',
        required: '非必填',
        more: {
          options: [],
          logic: {
            before: [],
          },
        },
      });
      break;
    case 'q-m':
      qArray.value.push({
        id: --fakeID.value,
        type: value,
        title: '',
        remark: '',
        required: '非必填',
        more: {
          options: [],
          logic: {
            before: [],
          },
        },
      });
      break;
    case 'q-fill':
      qArray.value.push({
        id: --fakeID.value,
        type: value,
        title: '',
        remark: '',
        required: '非必填',
        more: {
          checked: '',
          logic: {
            before: [],
          },
        },
      });
      break;
    case 'q-rate':
      qArray.value.push({
        id: --fakeID.value,
        type: value,
        title: '',
        remark: '',
        required: '非必填',
        more: {
          rate: 5,
          logic: {
            before: [],
          },
        },
      });
      break;
    case 'q-locate':
      qArray.value.push({
        id: --fakeID.value,
        type: value,
        title: '',
        remark: '',
        required: '非必填',
        more: {
          logic: {
            before: [],
          },
        },
      });
      break;
    case 'eq-s':
      qArray.value.push({
        id: --fakeID.value,
        type: value,
        title: '',
        remark: '',
        required: '非必填',
        more: {
          logic: {
            before: [],
          },
          score: 0,
          options: [],
        },
      });
      break;
    case 'eq-m':
      qArray.value.push({
        id: --fakeID.value,
        type: value,
        title: '',
        remark: '',
        required: '非必填',
        more: {
          score: 0,
          options: [],
          logic: {
            before: [],
          },
        },
      });
      break;
    case 'eq-fill':
      qArray.value.push({
        id: --fakeID.value,
        type: value,
        title: '',
        remark: '',
        required: '非必填',
        more: {
          checked: '',
          score: 0,
          logic: {
            before: [],
          },
        },
      });
      break;
  }
};

// 右侧导航栏scroll
const hashScrollTop = (index: any) => {
  document.getElementById('title').scrollIntoView();
};
const hashScroll = (index: any) => {
  document
    .getElementById(qArray.value[index].type + qArray.value[index].id)
    .scrollIntoView();
};

// 更多操作
const moreActions = [
  {
    label: '禁止拖动排序',
    value: 'drag',
  },
  {
    label: '保存同时发布',
    value: 'release',
  },
  {
    label: '不显示题号',
    value: 'index',
  },
];
const moreValue = ref(null);

// 是否发布
const draggable = computed(() => {
  if (!moreValue.value) return true;
  return (moreValue.value as any).indexOf('drag') >= 0 ? false : true;
});
// 是否发布
const isReleased = computed(() => {
  if (!moreValue.value) return false;
  return (moreValue.value as any).indexOf('release') >= 0 ? true : false;
});
// 是否显示题号
const showIndex = computed(() => {
  if (!moreValue.value) return true;
  return (moreValue.value as any).indexOf('index') >= 0 ? false : true;
});
// 打印
const print = () => {
  window.print();
};
// 预览
const previewActive = ref(false);
const preview = () => {
  // let preview = router.resolve({
  //   path: '/q/preview',
  //   query: {
  //     title: title.value,
  //     note: note.value,
  //     qArray: JSON.stringify(qArray),
  //     showIndex: showIndex.value.toString(),
  //   },
  // });
  // window.open(preview.href, '_blank');
  previewActive.value = true;
  window.$message.info('预览完毕后可以在右上角关闭哦', {
    duration: 2000,
  });
};
//提交问卷前的验证
const validate = () => {
  console.log(qArray.value);
  if (title.value == '') {
    return false;
  }
  for (var i = 0; i < qArray.value.length; i++) {
    if (qArray.value[i].title == '') {
      return false;
    }
    if (
      qArray.value[i].type == 'q-s' ||
      qArray.value[i].type == 'q-m' ||
      qArray.value[i].type == 'eq-s' ||
      qArray.value[i].type == 'eq-m'
    ) {
      for (var j = 0; j < qArray.value[i].more.options.length; j++) {
        if (qArray.value[i].more.options[j] == '') {
          return false;
        }
      }
    }
    if (qArray.value[i].type == 'q-apply') {
      for (var j = 0; j < qArray.value[i].more.applys.length; j++) {
        if (
          qArray.value[i].more.applys[j].option == '' ||
          qArray.value[i].more.applys[j].left == 0
        ) {
          return false;
        }
      }
    }
  }
  return true;
};
// 定时保存
const save = () => {
  if (!validate()) {
    return;
  }
  Ques.saveQ({
    id: id.value,
    type: Number(props.type),
    title: title.value,
    note: note.value,
    qStatus: isReleased.value === true ? 1 : 0,
    amount: amount.value,
    content: qArray.value,
    showIndex: showIndex.value,
  }).then((res: any) => {
    console.log(qArray.value);
    console.log(res);
    // console.log(res.data);
    if (res.data.status === 200) {
      window.$message.success('定时保存成功！');
      id.value = res.data.data.id;
    }
  });
};
// 提交问卷
const submit = () => {
  if (!validate()) {
    message.error('问卷题目或者选项内容未填写！');
    return;
  }
  console.log('submit', {
    id: id.value,
    type: Number(props.type),
    title: title.value,
    note: note.value,
    qStatus: isReleased.value === true ? 1 : 0,
    amount: amount.value,
    content: qArray.value,
    showIndex: showIndex.value,
  });
  Ques.saveQ({
    id: id.value,
    type: Number(props.type),
    title: title.value,
    note: note.value,
    qStatus: isReleased.value === true ? 1 : 0,
    amount: amount.value,
    content: qArray.value,
    showIndex: showIndex.value,
  }).then((res: any) => {
    console.log(qArray.value);
    console.log(res);
    // console.log(res.data);
    if (res.data.status === 200) {
      router.push('/q/a/' + props.type + '/' + res.data.data.id + '/send');
      window.$message.success('提交成功！');
    } else {
      window.$message.error('提交失败！');
    }
  });
};

// const webkitGrab = computed(() => {
//   return '-webkit-' + Grab.value;
// });
// const mozGrab = computed(() => {
//   return '-moz-' + Grab.value;
// });
// const Grab = ref('grab');

// 更改问卷类型
const showModal = ref(false);
const createQ = (index: Number) => {
  showModal.value = false;
  router.replace('/q/create/' + index.toString() + '/0');
  console.log(props.type);
  setTimeout(() => {
    initQ();
  }, 300);
};
const posConfirm = () => {
  show();
};
const nagConfirm = () => {};
const show = () => {
  if (!store.state.auth) {
    router.push('/login');
  } else {
    showModal.value = true;
  }
};

// 计算考试总分
const calSumScore = () => {
  if (props.type === '1') {
    let sum = 0;
    qArray.value.forEach((ele: any) => {
      if (!ele.type.startsWith('eq')) {
        return;
      }
      sum += ele.more.score;
    });
    return sum;
  }
  return 0;
};
</script>

<style scoped lang="scss">
.q-out {
  background: url('@images/login-bg.png');
  // background-size: 100%;
  background-position: -10.7vw -33vh; /*这个是按从左往右，从上往下的百分比位置进行调整*/
}
.q {
  background-color: rgb(255, 255, 255, 0.5);
  // background: url('@images/bg-2.png');
  // background: url('@images/bg-1.png');
  // background-size: 100%;
  // background-position: 20% -0.5%; /*这个是按从左往右，从上往下的百分比位置进行调整*/
  // &-sider {
  // background: url('@images/wl-1.jpg');
  // background: url('@images/bg-2.png');
  // }
  &-page {
    background-color: rgb(255, 255, 255, 0.98);
    padding: 2vh 2vw 2vh 2vw;
    border-radius: 1vw;
    box-shadow: -1px -1px 36px -12px rgba(170, 170, 170, 0.7);
    -webkit-box-shadow: -1px -1px 36px -12px rgba(170, 170, 170, 0.7);
    -moz-box-shadow: -1px -1px 36px -12px rgba(170, 170, 170, 0.7);
  }
  min-height: 90vh;
}

// // 右侧栏
// .side {
//   width: 10vw;
//   position: absolute;
//   right: 2vw;
//   top: 3vh;
// }

// 题目右侧选择栏
.side-option {
  height: 14vh;
  margin-top: -1vh;
  button {
    margin: 2px;
  }
}

// 让拖拽下方不可见
.sortable {
  &-ghost {
    visibility: hidden;
  }
}

// 提交栏
.q-submit {
  min-width: 10vw;
  max-width: 10vw;
  top: 50vh;
  right: 3vw;
  button {
    font-size: 0.5rem;
    width: 10vw;
  }
}

// 抽屉高度
:deep(.n-drawer.n-drawer--bottom-placement) {
  height: 100vh !important;
}

// 设置抓取pointer
:deep(.n-collapse-item__header) {
  cursor: move !important;
}

// 左侧导航栏
:deep(.n-menu) {
  // background-color: rgba(255, 255, 255, 0.8) !important;
}
div.n-layout-sider-scroll-container div {
  position: fixed;
  top: 12vh;
}
:deep(.n-layout-sider) .n-layout-toggle-bar {
  position: fixed;
  top: 45vh;
  right: auto;
  margin-right: -1.5vw;
}
:deep(.n-menu) .n-menu-item-content {
  padding-right: 45px !important;
}

//坍缩后宽度
:deep(.n-menu--collapsed) .n-menu-item {
  width: 3rem;
}
</style>
